package com.zd.springsecuritydemo.service.impl;

import com.alibaba.fastjson.JSON;
import com.zd.springsecuritydemo.pojo.entity.User;
import com.zd.springsecuritydemo.response.LoginUser;
import com.zd.springsecuritydemo.response.ResponseResult;
import com.zd.springsecuritydemo.service.LoginService;
import com.zd.springsecuritydemo.util.JwtUtil;
import com.zd.springsecuritydemo.util.RedisCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author ZhangDong
 * @date 2024/1/7 13:39
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {
    private final AuthenticationManager authenticationManager;
    private final RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        // 通过AuthenticationManager的authenticate方法来进行用户认证
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(token);
        //如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        //如果认证通过了，使用userid生成一个jwt jwt返回给前端
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long id = loginUser.getUser().getId();
        String jwt = JwtUtil.createJWT(id.toString());
        //把完整的用户信息存入redis userid为key
        redisCache.setCacheObject("login:" + id, loginUser);
        return new ResponseResult(200, "登录成功", jwt);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        User user = loginUser.getUser();
        String key = "login:" + user.getId();
        redisCache.deleteObject(key);
        return new ResponseResult(200, "注销成功");
    }

}
